<template>
  <div :style="'width:' + width">
    <div class="form-item-label-top">
      <span style="color: red; margin-right: 5px" v-if="required">*</span>
      <div>{{ name }}</div>
    </div>
    <div
      style="display: flex; align-items: center; margin: 10px"
      v-if="caseVis"
    >
      <div style="width: 70px">报销案件：</div>
      <el-select
        style="flex: 1"
        v-model="data.caseId"
        filterable
        remote
        reserve-keyword
        placeholder="请输入（被保险人/处理机构/委托日期等）关键词搜索"
        :remote-method="getCases"
        :loading="loading"
        @input="chooseCase"
      >
        <el-option
          v-for="item in cases"
          :key="item.CS_ID"
          :label="'[' + item.CS_ID + ']' + item.CS_DisplayName"
          :value="item.CS_ID"
        ></el-option>
      </el-select>
      <el-button
        v-if="curCase"
        size="small"
        icon="el-icon-more"
        @click="detailVis = !detailVis"
      ></el-button>
    </div>
    <div v-if="detailVis && curCase" style="margin: 20px">
      <div>所属部门：{{ curCase.DPM_Name }}</div>
      <div>流程：{{ curCase.FLOW_Name }}</div>
      <el-link style="color: blue" @click="toCase(curCase.CS_ID)">
        <i class="el-icon-search"></i>
        流水号：{{ curCase.CS_No }}
      </el-link>
      <div>案件名称：{{ curCase.CS_DisplayName }}</div>
      <div>案件状态：{{ curCase.CS_StatusDesc }}</div>
      <div>事故地区：{{ curCase.CS_AccidentAreaDesc }}</div>
      <div>事故时间：{{ curCase.CS_AccidentTime | formatTime }}</div>
      <div>事故原因：{{ curCase.CS_AccidentReason }}</div>
      <div>报销类型：{{ curCase.EXTY_EnumTxt }}</div>
      <div>估损金额：{{ curCase.CS_EstimateLossFee }}元</div>
      <div>定损金额：{{ curCase.CS_LossFee }}元</div>
      <div>报损金额：{{ curCase.CS_ReportLossFee }}元</div>
      <div>理算金额：{{ curCase.CS_AdjustmentFee }}元</div>
      <div>委托日期：{{ curCase.CS_DelegationDate | formatDate }}</div>
      <div>允许添加日志：{{ curCase.CS_AllowLog ? '允许' : '不允许' }}</div>
      <div>允许报销：{{ curCase.CS_AllowExpense ? '允许' : '不允许' }}</div>
    </div>
    <div
      style="display: flex; align-items: center; margin: 10px"
      v-if="caseVis && curCase"
    >
      <div style="width: 70px">报销日志：</div>
      <el-select
        style="flex: 1"
        v-model="data.logId"
        filterable
        placeholder="请选择日志"
        @input="chooseLog"
      >
        <el-option
          v-for="item in curCase.Logs"
          :key="item.CLG_ID"
          :label="item.CLG_DisplayName"
          :value="item.CLG_ID"
        ></el-option>
      </el-select>
      <el-button
        v-if="curLog"
        size="small"
        icon="el-icon-more"
        @click="logDetailVis = !logDetailVis"
        :disabled="false"
      ></el-button>
    </div>
    <div v-if="logDetailVis">
      <div v-if="logDetailVis" style="margin: 20px">
        <div>提交人：{{ curLog.USR_Name }}</div>
        <div>联系电话：{{ curLog.USR_Phone | encodePhone }}</div>
        <div>流程：{{ curLog.FLOW_Name }}</div>
        <div>
          作业时间：{{ curLog.CLG_StartTime | formatDate }}至{{
            curLog.CLG_EndTime | formatDate
          }}
        </div>
        <div>作业内容：{{ curLog.CLG_Content }}</div>
      </div>
    </div>
    <div
      style="display: flex; align-items: center; margin: 10px"
      v-if="caseVis && curCase"
    >
      <div style="width: 70px">支付人：</div>
      <el-select
        style="flex: 1"
        v-model="data.empId"
        filterable
        placeholder="请选择案件成员"
        @input="chooseEmp"
      >
        <el-option
          v-for="item in curCase.Employees"
          :key="item.CSEP_ID"
          :label="'[' + item.CSEP_TypeDesc + ']' + item.USR_Name"
          :value="item.CSEP_ID"
        ></el-option>
      </el-select>
      <el-button
        v-if="curEmp"
        size="small"
        icon="el-icon-more"
        @click="empDetailVis = !empDetailVis"
        :disabled="false"
      ></el-button>
    </div>
    <div v-if="empDetailVis" style="margin: 20px">
      <div>公司：{{ curEmp.CMP_Name }}</div>
      <div v-if="curEmp.USR_Name">员工：{{ curEmp.USR_Name }}</div>
      <div>联系电话：{{ curEmp.USR_Phone | encodePhone }}</div>
    </div>
    <el-table :data="data.invoices" stripe border highlight-current-row>
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form label-position="left" inline class="invoice-table-expand">
            <el-form-item label="编号" v-if="scope.row.IN_No">
              <span>{{ scope.row.IN_No }}</span>
            </el-form-item>
            <el-form-item label="报销性质" v-if="scope.row.INTY_EnumTxt">
              <span>{{ scope.row.INTY_EnumTxt }}</span>
            </el-form-item>
            <el-form-item label="地址" v-if="scope.row.IN_AreaDesc">
              <span>{{ scope.row.IN_AreaDesc }}</span>
            </el-form-item>
            <el-form-item label="开票日期" v-if="scope.row.IN_DealDate">
              <span>{{ scope.row.IN_DealDate | formatDate }}</span>
            </el-form-item>
            <el-form-item label="实际发生日期" v-if="scope.row.IN_UsedDate">
              <span>{{ scope.row.IN_UsedDate | formatDate }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="票据">
        <template slot-scope="scope">
          <a
            @click="
              imageSrc = fileURL + scope.row.FL_SrcPath
              imageVis = true
            "
          >
            {{ scope.row.INTY_EnumTxt ? `[${scope.row.INTY_EnumTxt}]` : '' }}
            {{ scope.row.FL_Name }}
          </a>
        </template>
      </el-table-column>
      <el-table-column label="发票金额" width="90px">
        <template slot-scope="scope">{{ scope.row.IN_Fee }}元</template>
      </el-table-column>
      <el-table-column label="报销金额" width="120px">
        <template slot-scope="scope">
          <el-input
            style="background: red"
            v-model="scope.row.ExpenseFee"
            placeholder="请输入报销金额"
            @input="input"
            :disabled="disabled"
            :suffix-icon="
              scope.row.ExpenseFee == scope.row.IN_Fee
                ? ''
                : 'el-icon-warning-outline'
            "
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="备注" width="150px">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.ExpenseRemark"
            placeholder="请输入备注"
            @input="input"
            :disabled="disabled"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column width="50px">
        <template slot="header">
          <el-button
            size="medium"
            type="text"
            slot="reference"
            icon="el-icon-plus"
            v-if="addEnable"
            :disabled="disabled"
            @click="
              getInvoices()
              chooseInvoices = [...data.invoices]
              chooseInvoiceVis = true
            "
          ></el-button>
        </template>
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-delete"
            :disabled="disabled"
            @click="removeInvoice(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="color: #888; font-size: 12px; margin: 10px">
      {{ data.displayName }}
    </div>
    <el-dialog
      :visible.sync="chooseInvoiceVis"
      width="80%"
      :title="'选择' + name"
      :modal-append-to-body="false"
    >
      <div class="header">
        <span style="margin-left: 20px">关键字</span>
        <el-input
          placeholder="请输入关键字"
          v-model="invoiceReq.keyword"
          style="width: 200px; margin-left: 10px"
          clearable
        ></el-input>

        <span style="margin-left: 20px">报销日期</span>
        <el-date-picker
          style="width: 200px; margin-left: 10px"
          v-model="invoiceReq.dealDate1"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="date"
          placeholder="选择报销日期"
        ></el-date-picker>
        -
        <el-date-picker
          v-model="invoiceReq.dealDate2"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="date"
          placeholder="选择报销日期"
        ></el-date-picker>
        <el-button
          type="default"
          style="margin-left: 20px"
          size="small"
          @click="
            invoiceReq.pageIndex = 1
            getInvoices()
          "
        >
          搜索
        </el-button>
      </div>
      <div style="height: 460px">
        <el-table
          style="overflow: auto"
          height="400px"
          :data="invoiceRes.Items"
          stripe
          border
          highlight-current-row
        >
          <el-table-column type="index" width="40"></el-table-column>
          <el-table-column width="60" label="勾选">
            <template slot-scope="scope">
              <el-checkbox
                :value="
                  chooseInvoices.findIndex((x) => x.IN_ID == scope.row.IN_ID) !=
                  -1
                "
                @change="invoiceCheckChange(scope.row)"
              ></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="发票号码" width="120">
            <template slot-scope="scope">
              <el-popover
                placement="top-start"
                trigger="hover"
                v-if="scope.row.IN_No"
              >
                <div>[{{ scope.row.IN_ID }}]{{ scope.row.IN_No }}</div>
                <div slot="reference">
                  {{
                    scope.row.IN_No.length > 10
                      ? scope.row.IN_No.substring(0, 10) + '...'
                      : scope.row.IN_No
                  }}
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="发票金额" width="100">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                icon="el-icon-picture"
                @click="
                  imageSrc = fileURL + scope.row.FL_SrcPath
                  imageVis = true
                "
              ></el-button>
              {{ scope.row.IN_Fee }}元
            </template>
          </el-table-column>
          <el-table-column label="开票日期" width="100">
            <template slot-scope="scope">
              {{ scope.row.IN_DealDate | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="实际发生日期" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.IN_UsedDate | formatDate }}</span>
            </template>
          </el-table-column>
          <el-table-column label="报销性质" width="80">
            <template slot-scope="scope">
              {{ scope.row.INTY_EnumTxt }}
            </template>
          </el-table-column>
          <el-table-column label="报销地址">
            <template slot-scope="scope">
              {{ scope.row.IN_AreaDesc }}
            </template>
          </el-table-column>
          <el-table-column label="抬头" width="260">
            <template slot-scope="scope">
              {{ scope.row.IN_Title }}
            </template>
          </el-table-column>
          <el-table-column label="备注">
            <template slot-scope="scope">
              {{ scope.row.IN_Remark }}
            </template>
          </el-table-column>
        </el-table>
        <div
          style="
            display: flex;
            align-items: center;
            height: 50px;
            justify-content: space-between;
          "
        >
          <el-pagination
            layout="total,prev,pager,next,sizes"
            background
            :current-page.sync="invoiceReq.pageIndex"
            :page-size="invoiceReq.pageSize"
            :total="invoiceRes.Total"
            :page-sizes="[10, 15]"
            @size-change="
              (val) => {
                invoiceReq.pageSize = val
                getInvoices()
              }
            "
            @current-change="getInvoices()"
          ></el-pagination>
          <el-button
            type="primary"
            @click="chooseSure"
            style="
              right: 50px;
              bottom: 40px;
              width: 80px;
              height: 40px;
              font-size: 16px;
            "
          >
            确定
          </el-button>
        </div>
      </div>
    </el-dialog>

    <el-image-viewer
      style="z-index: 9999"
      v-if="imageVis"
      :url-list="[imageSrc]"
      :on-close="closeImage"
    ></el-image-viewer>
  </div>
</template>
<script>
import elImageViewer from 'element-ui/packages/image/src/image-viewer'
import {
  getInvoices,
  getCases,
  getCase,
} from '@/api/flowCenter/field/quickExpenseForm'
import { baseURL, fileRoot } from '@/config'
export default {
  components: { elImageViewer },
  props: ['value', 'disabled', 'props', 'required', 'isBusiness', 'creatorId'],
  data: function () {
    return {
      imageSrc: '',
      invoiceReq: {
        keyword: '',
        dealDate: null,
        pageIndex: 1,
        pageSize: 10,
      },
      invoiceRes: {
        Items: [],
        Total: 0,
      },
      caseReq: {
        keyword: '',
        travelDates: [],
      },
      cases: [],
      curCase: null,
      curLog: null,
      curEmp: null,

      data: {
        invoices: [],
        displayName: '',
        caseId: null,
        logId: null,
        empId: null,
      },
      chooseInvoices: [],
      chooseInvoiceVis: false,

      loading: false,
      caseVis: false,
      detailVis: false,
      logDetailVis: false,
      empDetailVis: false,
      imageVis: false,
      fileURL: baseURL + fileRoot,
      addEnable: false,
    }
  },
  computed: {
    myprops() {
      return this.props ? this.props : []
    },
    width() {
      let val = this.myprops.find((x) => x.FLPR_Code == 'width')
      if (val) {
        if (this.isBusiness) {
          return val.BFFP_Value ? val.BFFP_Value : '100%'
        } else {
          return val.FFLP_Value ? val.FFLP_Value : '100%'
        }
      }
      return '100%'
    },
    name() {
      let val = this.myprops.find((x) => x.FLPR_Code == 'name')
      if (val) {
        if (this.isBusiness) {
          return val.BFFP_Value ? val.BFFP_Value : '快速报销'
        } else {
          return val.FFLP_Value ? val.FFLP_Value : '快速报销'
        }
      }
      return '快速报销'
    },
  },
  methods: {
    toCase(caseId) {
      this.$router.push({
        name: 'caseInfoPage',
        query: { caseId },
      })
    },
    closeImage() {
      this.imageVis = false
      return true
    },
    getInvoices() {
      this.loading = true
      getInvoices(this.invoiceReq).then(({ data }) => {
        this.invoiceRes = data
        this.loading = false
      })
    },
    removeInvoice(invoice) {
      this.data.invoices.splice(
        this.data.invoices.findIndex((x) => x.IN_ID == invoice.IN_ID),
        1
      )
      this.input()
    },
    invoiceCheckChange(invoice) {
      let index = this.chooseInvoices.findIndex((x) => x.IN_ID == invoice.IN_ID)
      if (index == -1) {
        this.chooseInvoices.push({
          ...invoice,
          ExpenseFee: invoice.IN_Fee,
          ExpenseRemark: '',
        })
      } else {
        this.chooseInvoices.splice(index, 1)
      }
      console.log(invoice)
    },
    chooseSure() {
      this.data.invoices = [...this.chooseInvoices]
      // console.log(this.data.invoices)
      this.caseReq.travelDates = this.chooseInvoices.map((x) => x.IN_UsedDate)
      console.log(this.caseReq.travelDates)
      this.loading = true
      getCases(this.caseReq).then(({ data }) => {
        this.cases = data
        if (this.cases.length > 0) {
          this.chooseCase(this.cases[0].CS_ID)
        }
        this.loading = false
        this.caseVis = true
      })
      this.chooseInvoiceVis = false
    },
    getCases(keyword) {
      if (keyword.length >= 2) {
        this.loading = true
        this.caseReq.keyword = keyword
        this.caseReq.travelDates = null //用关键字搜索时说明在案件自动搜索中查不到相关案件，所以不需要出差日期
        getCases(this.caseReq).then(({ data }) => {
          this.cases = data
          if (this.cases.length > 0) {
            this.chooseCase(this.cases[0].CS_ID)
          }
          this.loading = false
        })
      }
    },
    chooseCase(val) {
      this.data.caseId = val
      getCase(val).then(({ data }) => {
        this.curCase = data
        // if (this.curCase.Logs.length > 0) {
        //   this.chooseLog(this.curCase.Logs[0].CLG_ID)
        // }
        if (this.curCase.Employees.length > 0) {
          this.chooseEmp(this.curCase.Employees[0].CSEP_ID)
        }
        this.input()
      })
    },
    chooseLog(val) {
      this.data.logId = val
      this.curLog = this.curCase.Logs.find((x) => x.CLG_ID == val)
      this.input()
    },
    chooseEmp(val) {
      this.data.empId = val
      this.curEmp = this.curCase.Employees.find((x) => x.CSEP_ID == val)
      this.input()
    },
    input() {
      let invoiceSum = 0
      let expenseSum = 0
      this.data.invoices.forEach((x) => {
        invoiceSum += Number(x.IN_Fee)
        expenseSum += Number(x.ExpenseFee)
      })
      this.data.displayName = `票据${
        this.data.invoices.length
      }张，发票金额共${invoiceSum.toFixed(2)}元，报销金额共${expenseSum.toFixed(
        2
      )}元`
      //，报销至【${this.curCase.CS_DisplayName}】中。
      this.$emit('input', JSON.stringify(this.data))
      this.$emit('display', this.data.displayName)
    },
  },
  mounted: function () {
    let empId = this.$store.getters['user/curEmp'].EMP_ID
    //只有表单发起人才允许添加票据
    this.addEnable = empId == this.creatorId || !this.creatorId
    if (this.value && Object.keys(this.value).length) {
      this.data = JSON.parse(this.value)
      getCase(this.data.caseId).then(({ data }) => {
        this.cases = [data]
        this.curCase = data
        this.curLog = this.curCase.Logs.find((x) => x.CLG_ID == this.data.logId)
        this.curEmp = this.curCase.Employees.find(
          (x) => x.CSEP_ID == this.data.empId
        )
      })
      this.caseVis = true
    }
  },
}
</script>

<style>
.el-input__suffix {
  color: red;
  font-size: 14px;
}
</style>
<style scoped>
.header {
  width: 100%;
  padding-bottom: 10px;
  height: auto;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  background: #ffffff;
  border-radius: 5px;
  border-bottom: #f4f8ff 2px solid;
  display: flex;
  margin-bottom: 11px;
  align-items: center;
}
.el-form-item {
  margin: 10px !important;
}
</style>
<style>
.invoice-table-expand {
  font-size: 0;
}
.invoice-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.invoice-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>